package com.googlecode.publicholiday.repository;

import com.googlecode.publicholiday.repository.jdbc.AbstractJdbcImmutablePublicHolidayRepository;
import org.joda.time.LocalDate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;

import static org.springframework.dao.support.DataAccessUtils.singleResult;

@Repository
public class SpringJdbcImmutablePublicHolidayRepository extends AbstractJdbcImmutablePublicHolidayRepository {

    protected final JdbcTemplate jdbcTemplate;

    public SpringJdbcImmutablePublicHolidayRepository(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @Override
    public LocalDate find(String countryCode, LocalDate publicHoliday) {
        return singleResult(jdbcTemplate.query(
                getPublicHolidayOnDateSqlStatement(),
                new LocalDateRowMapper(),
                countryCode,
                new Date(publicHoliday.toDate().getTime())));
    }

    @Override
    public Collection<LocalDate> find(String countryCode, LocalDate startDate, LocalDate endDate) {
        return jdbcTemplate.query(
                getPublicHolidaysBetweenDatesSqlStatement(),
                new LocalDateRowMapper(),
                countryCode,
                new Date(startDate.toDate().getTime()),
                new Date(endDate.toDate().getTime()));
    }

    private static class LocalDateRowMapper implements RowMapper<LocalDate> {
        @Override
        public LocalDate mapRow(ResultSet rs, int rowNum) throws SQLException {
            return new LocalDate(rs.getDate(1).getTime());
        }
    }

}
